const path = require('path')

const pathArray2Tree = (files,rootPath='/')=> {

    files = files.reduce(function(tree, f) {
        let dir = path.dirname(f.path)

        if(f.path!=dir){
            if (tree[dir]) {
                tree[dir].children.push(f)
            } else {
                tree[dir] = { children: [f] }
            }
        }

        if (tree[f.path]) {
            f.children = tree[f.path].children
        } else {
            if(f.type=='folder'){
                f.children = []
            }
        }

        tree[f.path] = f

        return tree
    }, {})

    return files[rootPath]?.children||[]
}

const wrapResponse = (ctx,files,path,treeMode=true)=>{
    let baseUrl = encodeURI(`${ctx.user.shareLink}/download`)
    if(treeMode&&files.length){
        files = pathArray2Tree(files,path)
    }
    return {files,baseUrl,path}
}

module.exports = {wrapResponse}
